package com.dawn.module.hospital.service.invoice;

import com.dawn.framework.mybatis.core.query.LambdaQueryWrapperX;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import org.springframework.validation.annotation.Validated;

import java.util.*;
import com.dawn.module.hospital.controller.admin.invoice.vo.*;
import com.dawn.module.hospital.dal.dataobject.invoice.InvoiceDO;
import com.dawn.framework.common.pojo.PageResult;
import com.dawn.framework.common.util.object.BeanUtils;

import com.dawn.module.hospital.dal.mysql.invoice.InvoiceMapper;

import static com.dawn.framework.common.exception.util.ServiceExceptionUtil.exception;
import static com.dawn.module.hospital.enums.ErrorCodeConstants.*;

/**
 * 发票 Service 实现类
 *
 * @author root
 */
@Service
@Validated
public class InvoiceServiceImpl implements InvoiceService {

    @Resource
    private InvoiceMapper invoiceMapper;

    @Override
    public Long createInvoice(InvoiceSaveReqVO createReqVO) {
        // 插入
        InvoiceDO invoice = BeanUtils.toBean(createReqVO, InvoiceDO.class);
        invoiceMapper.insert(invoice);
        // 返回
        return invoice.getId();
    }

    @Override
    public void updateInvoice(InvoiceSaveReqVO updateReqVO) {
        // 校验存在
        validateInvoiceExists(updateReqVO.getId());
        // 更新
        InvoiceDO updateObj = BeanUtils.toBean(updateReqVO, InvoiceDO.class);
        invoiceMapper.updateById(updateObj);
    }

    @Override
    public void deleteInvoice(Long id) {
        // 校验存在
        validateInvoiceExists(id);
        // 删除
        invoiceMapper.deleteById(id);
    }

    private void validateInvoiceExists(Long id) {
        if (invoiceMapper.selectById(id) == null) {
            throw exception(INVOICE_NOT_EXISTS);
        }
    }

    @Override
    public InvoiceDO getInvoice(Long id) {
        return invoiceMapper.selectById(id);
    }

    @Override
    public InvoiceDO getInvoiceByOrderNumber(String orderNumber) {
        InvoiceDO invoiceDO = null;
        LambdaQueryWrapperX<InvoiceDO> queryWrapperX = new LambdaQueryWrapperX<>();
        queryWrapperX.eq(InvoiceDO::getOrderNumber,orderNumber).orderByDesc(InvoiceDO::getCreateTime);
        List<InvoiceDO> selectList = invoiceMapper.selectList(queryWrapperX);
        if(selectList.size()>0){
            invoiceDO = selectList.get(0);
        }
        return invoiceDO;
    }

    @Override
    public PageResult<InvoiceDO> getInvoicePage(InvoicePageReqVO pageReqVO) {
        return invoiceMapper.selectPage(pageReqVO);
    }

}